#!/usr/bin/python3
# -*- coding: utf-8 -*-

from typing import Any, Dict, List, Literal

import allure
from playwright.sync_api import Page

from constant.product_status import LeaseStatus
from models.base_page import BasePage
from models.network_page.dns_aliase_page.dns_aliase_page import DnsAliasePage
from models.network_page.eip_page.eip_page import EIPPage
from models.network_page.intranet_router_page.intranet_router_page import \
    IntranetRouterPage
from models.network_page.loadbalancer_page.loadbalancer_page import \
    LoadbalancerPage
from models.network_page.loadbalancer_page.loadbalancer_policie_page import \
    LoadbalancerPoliciePage
from models.network_page.loadbalancer_page.server_certificate_page import \
    ServerCertificatePage
from models.network_page.nat_page.nat_page import NATPage
from models.network_page.network_acl_page.network_acl_page import \
    NetworkAclPage
from models.network_page.network_acl_page.security_policie_page import \
    SecurityPoliciePage
from models.network_page.router_page.router_page import RouterPage
from models.network_page.routing_table_page.routing_table_page import \
    RoutingTablePage
from models.network_page.security_group_page.rule_subset_page import \
    RuleSubsetPage
from models.network_page.security_group_page.security_group_ipsets_page import \
    SecurityGroupIpsetsPage
from models.network_page.security_group_page.security_group_page import \
    SecurityGroupsPage
from models.network_page.span_page.span_page import SpanPage
from models.network_page.vip_page.vip_page import VipPage
from models.network_page.vxnet_page.vxnet_page import VxnetPage
from utils.log import log
from utils.valid_util import case_assert


class VxnetBusiness(BasePage):
    def __init__(self, page: Page):
        super().__init__(page)
        self.vxnet_page = VxnetPage(page)

    def navigate_to_vxnet_page(self, region=None):
        """导航到私有网络页面"""
        with allure.step(f"导航到:{region} 私有网络列表页"):
            super().navigate(region, self.vxnet_page.route)
            self.expect.to_have_title("私有网络")
            self.expect.to_have_url(self.vxnet_page.route)

    def create_vxnet(self, vxnet_name: str = "") -> List[str]:
        with allure.step(f"创建私有网络，名称:{vxnet_name}"):
            self.vxnet_page.create_vxnet_but()
            self.vxnet_page.input_vxnet_name(vxnet_name)
            with self.page.expect_response(self.api_action("CreateVxnets"), timeout=self.api_timeout) as resp:
                self.vxnet_page.click_create_submit_but()
                # self.page.wait_for_timeout(self.wait_response_timeout)
            response = resp.value
            res = response.json()
            log.debug(f"{res}")
            case_assert.assert_code(res)
            vxnets = res["vxnets"]
            log.info(f"创建的私有网络ID为:{vxnets}")
            return vxnets

    def delete_vxnet_from_home_page(self, vxnet_keyword: str = "") -> Dict[str, Any]:
        """删除私有网络"""
        with allure.step(f"删除私有网络:{vxnet_keyword}"):
            self.vxnet_page.delte_vxnet_by_name(vxnet_keyword)
            self.toolbar.more_operations_button()
            self.toolbar.more_operations_button_to_delete("删除")
            with self.page.expect_response(self.api_action("DeleteVxnets"), timeout=self.api_timeout) as resp:
                alert_text_content = self.vxnet_page.get_delete_vxnet_alert_info()
                if alert_text_content:
                    self.popout.click_alert_confirm_button_by_role_link()
                # self.page.wait_for_timeout(self.wait_response_timeout)
            response = resp.value
            res = response.json()
            log.debug(f"{res}")
            case_assert.assert_code(res)
            vxnets = res.get('vxnets')
            log.info(f"删除的私有网络为:{vxnets}")
            return vxnets

    def modify_vxnet_attributes(self, vxnet_name: str = '', description: str = '') -> None:
        """修改私有网络属性"""
        with allure.step(f"修改私有网络属性名称:{vxnet_name},描述:{description}"):
            if vxnet_name:
                self.vxnet_page.input_vxnet_name(vxnet_name)
            if description:
                self.vxnet_page.input_description(description)
            with self.page.expect_response(self.api_action("ModifyVxnetAttributes"), timeout=self.api_timeout) as resp:
                self.vxnet_page.click_create_submit_but()
                # self.page.wait_for_timeout(self.wait_response_timeout)
            response = resp.value
            res = response.json()
            log.debug(f"{res}")
            case_assert.assert_code(res)
            return

    def join_router(self):
        """私有网络加入VPC网络"""
        with allure.step("加入VPC网络"):
            pass

    def leave_router(self, vxnet_keyword: str) -> None:
        """私有网络离开VPC网络"""
        with allure.step(f"私有网络:{vxnet_keyword} 离开VPC网络"):
            self.vxnet_page.delte_vxnet_by_name(vxnet_keyword)
            self.toolbar.more_operations_button()
            self.toolbar.click_leave_router_button()
            get_leave_router_alert_info = self.vxnet_page.get_leave_router_alert_info_text_content()
            if get_leave_router_alert_info:
                with self.page.expect_response(self.api_action("LeaveRouter"), timeout=self.api_timeout) as resp:
                    self.popout.click_alert_confirm_button_by_role_link()
                    # self.page.wait_for_timeout(self.wait_response_timeout)
                response = resp.value
                res = response.json()
                log.debug(f"{res}")
                case_assert.assert_code(res)
                router_id = res.get('router_id')
                vxnets = res.get('vxnets')
                self.message.wait_message()
                self.wait_jobs(res, check_status=True)
                log.info(f"{vxnets} 从 {router_id} 离开成功")


class RouterBusiness(BasePage):
    def __init__(self, page: Page):
        super().__init__(page)
        self.router_page = RouterPage(page)

    def navigate_to_router_page(self, region=None):
        """导航到VPC网络列表页"""
        with allure.step(f"导航到:{region} VPC网络列表页"):
            super().navigate(region, self.router_page.route)
            self.expect.to_have_title("VPC 网络")
            self.expect.to_have_url(self.router_page.route)

    def create_router(self, zone_name='', router_name='', router_type='小型', eip_option='暂不绑定',
                      vxnet_name='') -> str:
        """
        创建VPC网络
        :param zone_name: 创建的区域
        :param router_name: vpc名称
        :param router_type: vpc类型
        :param eip_option: 是否绑定eip
        :param vxnet_name: vxnet名称
        :return: 返回vpc_id
        """
        with allure.step(f"创建VPC网络,名称:{router_name}"):
            self.router_page.click_create_router_button()
            self.router_page.create_page.select_zone(zone_name)
            self.router_page.create_page.fill_router_name(router_name)
            self.router_page.create_page.select_router_type(router_type)
            self.router_page.create_page.check_router_type_text_context(router_type)
            self.router_page.create_page.select_eip_type(eip_option)
            self.router_page.create_page.fill_vxnet_name(vxnet_name)
            with self.page.expect_response(self.api_action("CreateRouters"), timeout=self.api_timeout) as resp:
                self.router_page.create_page.click_submit_now_button()
                # self.page.wait_for_timeout(self.wait_response_timeout)
            response = resp.value
            res = response.json()
            log.debug(f"{res}")
            case_assert.assert_code(res)
            self.message.wait_message()
            routers = res.get('routers')
            router_id = routers[0]
            log.info(f"创建的VPC网络ID为:{router_id}")
            self.wait_jobs(res, check_status=True)
            self.wait_lease_status(routers, LeaseStatus.LEASE_STATUS_ACTIVE.value)
            self.expect.to_have_url(self.router_page.route)
            return router_id

    def delete_router_from_home_page(self, router_id_keyword: str = '') -> List[str]:
        """删除VPC网络"""
        with allure.step(f"删除VPC网络:{router_id_keyword}"):
            self.router_page.click_more_operation_button_by_keyword(router_id_keyword)
            self.router_page.click_delete_button()
            delete_router_alert_info = self.router_page.get_delete_router_alert_info_text_content()
            if delete_router_alert_info:
                with self.page.expect_response(self.api_action("DeleteRouters"), timeout=self.api_timeout) as resp:
                    self.popout.click_alert_confirm_button_by_role_link()
                    # self.page.wait_for_timeout(self.wait_response_timeout)
            response = resp.value
            res = response.json()
            log.debug(f"{res}")
            case_assert.assert_code(res)
            self.message.wait_message()
            routers = res.get('routers')
            log.info(f"删除的VPC网络ID为:{routers}")
            self.wait_jobs(res, check_status=True)
            self.wait_lease_status(routers, LeaseStatus.LEASE_STATUS_CEASED.value)
            return routers


class LoadbalancerBusiness(BasePage):
    def __init__(self, page: Page):
        super().__init__(page)
        self.loadbalancer_page = LoadbalancerPage(page)
        self.loadbalancer_policie_page = LoadbalancerPoliciePage(page)
        self.server_certificate_page = ServerCertificatePage(page)

    def navigate_to_loadbalancer_page(self, region=None):
        """导航到负载均衡器列表页"""
        with allure.step(f"导航到:{region} 负载均衡器列表页"):
            super().navigate(region, self.loadbalancer_page.route)
            self.expect.to_have_title("负载均衡器")
            self.expect.to_have_url(self.loadbalancer_page.route)

    def navigate_to_loadbalancer_policie_page(self, region=None):
        """导航到负载均衡器转发策略列表页"""
        with allure.step(f"导航到:{region} 负载均衡器转发策略列表页"):
            route = f"{self.loadbalancer_page.route}/{self.loadbalancer_policie_page.route}"
            super().navigate(region, route)
            self.expect.to_have_title("负载均衡器")
            self.expect.to_have_url(route)

    def navigate_to_server_certificates_page(self, region=None):
        """导航到负载均衡器服务器证书列表页"""
        with allure.step(f"导航到:{region} 负载均衡器服务器证书列表页"):
            route = f"{self.loadbalancer_page.route}/{self.server_certificate_page.route}"
            super().navigate(region, route)
            self.expect.to_have_title("负载均衡器")
            self.expect.to_have_url(route)


class RouteTableBusiness(BasePage):
    def __init__(self, page: Page):
        super().__init__(page)
        self.routing_table_page = RoutingTablePage(page)

    def navigate_to_routing_table_page(self, region=None):
        """导航到路由表列表页"""
        with allure.step(f"导航到:{region} 路由表列表页"):
            super().navigate(region, self.routing_table_page.route)
            self.expect.to_have_title("路由表")
            self.expect.to_have_url(self.routing_table_page.route)

    def create_route_table(self,
                           route_table_name: str,
                           route_table_type: Literal['vxnet', 'lb'] = 'vxnet',
                           navigate_to_home: bool = True,
                           region='') -> str:
        """
        创建路由表
        :param region: region name
        :param route_table_name: 路由表名称
        :param route_table_type: 路由表类型
        :param navigate_to_home: 是否返回到当前服务主页，默认返回主页
        :return:
        """
        with allure.step(f"创建路由表:{route_table_name},类型:{route_table_type}"):
            self.toolbar.create_button()
            self.routing_table_page.check_create_route_table_popout_title_to_be_visible()
            self.routing_table_page.type_route_table_name(route_table_name)
            if route_table_type == "vxnet":
                self.routing_table_page.click_vxnet_type()
            elif route_table_type == "lb":
                self.routing_table_page.click_lb_type()
            with self.page.expect_response(self.api_action("CreateRouteTable"), timeout=self.api_timeout) as resp:
                self.popout.click_submit_by_role_button()
            response = resp.value
            res = response.json()
            log.debug(f"{res}")
            case_assert.assert_code(res)
            routing_table = res.get('routing_table')
            log.info(f"创建的路由表ID为:{routing_table}")
            if navigate_to_home:
                if region:
                    self.navigate_to_routing_table_page(region)
                else:
                    self.navigate_to_routing_table_page()
            return routing_table

    def delete_route_table_from_home_page(self, keyword: str) -> List[str]:
        """删除路由表"""
        with allure.step(f"删除路由表:{keyword}"):
            self.table.click_checkbox_by_keyword(row_keyword=keyword)
            self.toolbar.more_operations_button()
            with self.page.expect_response(self.api_action("DeleteRouteTables"), timeout=self.api_timeout) as resp:
                self.toolbar.more_operations_button_to_delete("删除")
                alert_text_content = self.routing_table_page.get_delete_route_table_alert_info_text_content()
                if alert_text_content:
                    self.popout.click_alert_confirm_button_by_role_link()
            response = resp.value
            res = response.json()
            log.debug(f"{res}")
            case_assert.assert_code(res)
            routing_tables = res["routing_tables"]
            log.info(f"删除的路由表D为:{routing_tables}")
            return routing_tables


class EIPBusiness(BasePage):
    def __init__(self, page: Page):
        super().__init__(page)
        self.eip_page = EIPPage(page)

    def navigate_to_eip_ipv4_page(self, region=None):
        """导航到EIP_IPv4列表页"""
        with allure.step(f"导航到:{region} EIP_IPv4列表页"):
            route = f"{self.eip_page.route}/{self.eip_page.route1}"
            super().navigate(region, route)
            self.expect.to_have_title("弹性公网")
            self.expect.to_have_url(route)

    def navigate_to_eip_ipv6_page(self, region=None):
        """导航到EIP_IPv6列表页"""
        with allure.step(f"导航到:{region} EIP_IPv6列表页"):
            route = f"{self.eip_page.route}/{self.eip_page.route2}"
            super().navigate(region, route)
            self.expect.to_have_title("弹性公网")
            self.expect.to_have_url(route)

    def allocate_eips(self,
                      eip_name: str = '',
                      billing_mode: Literal["bandwidth", "traffic"] = 'bandwidth',
                      bandwidth: int = 1,
                      eip_group: str = '',
                      associate_mode: Literal["internal_binding", "external_binding"] = 'external_binding',
                      need_icp: bool = False,
                      count: int = 1,
                      ip_version: Literal["ipv4", "ipv6"] = 'ipv4') -> Dict[str, Any]:
        """申请公网EIP"""
        with allure.step(f"申请公网络EIP,名称:{eip_name},计费方式:{billing_mode},带宽:{bandwidth}"):
            self.eip_page.click_allocate_eip_button()
            warning_text_content = self.popout.get_alert_warning_text_content()
            if warning_text_content:
                if self.page.locator("#modalId").locator(".alert-warning").is_visible():
                    if ip_version == 'ipv4':
                        self.popout.click_continue_to_allocate_eip_by_role_link()
                    elif ip_version == 'ipv6':
                        self.popout.click_continue_to_allocate_eipv6_by_role_link()
            self.eip_page.input_eip_name(eip_name)
            self.eip_page.select_bandwidth_mode(billing_mode)
            self.eip_page.input_bandwidth_upper_limit(bandwidth)
            if eip_group:
                self.eip_page.select_ip_group(eip_group)
            self.eip_page.select_associate_mode(associate_mode)
            if need_icp:
                self.eip_page.select_need_icp()
            else:
                self.eip_page.select_need_icp('not_need_icp')
            self.eip_page.input_count(count)
            with self.page.expect_response(self.api_action("AllocateEips"), timeout=self.api_timeout) as resp:
                self.popout.click_submit_by_role_button()
                if self.eip_page.expect_ip_surcharge_title_to_be_visible():
                    self.popout.click_submit_by_role_link()
            response = resp.value
            res = response.json()
            log.debug(f"{res}")
            case_assert.assert_code(res)
            eips = res.get("eips")
            log.info(f"创建的公网IP IDs为:{eips}")
            self.wait_lease_status(eips, LeaseStatus.LEASE_STATUS_ACTIVE.value)
            return eips

    def release_eips_by_home(self, keyword: str) -> None:
        """释放公网EIP"""
        with allure.step(f"释放公网EIP:{keyword}"):
            self.table.click_checkbox_by_keyword(row_keyword=keyword)
            self.toolbar.more_operations_button()
            with self.page.expect_response(self.api_action("ReleaseEips"), timeout=self.api_timeout) as resp:
                self.toolbar.more_operations_button_to_delete("删除")
                alert_text_content = self.eip_page.get_release_eip_alert_warning_info()
                if alert_text_content:
                    self.popout.click_alert_confirm_button_by_role_button()
            response = resp.value
            res = response.json()
            log.debug(f"{res}")
            case_assert.assert_code(res)
            self.message.wait_message()
            self.wait_jobs(res, check_status=True)
            if keyword.startswith('eip-'):
                self.wait_lease_status([keyword], LeaseStatus.LEASE_STATUS_CEASED.value)


class NATBusiness(BasePage):
    def __init__(self, page: Page):
        super().__init__(page)
        self.nat_page = NATPage(page)

    def navigate_to_nat_page(self, region=None):
        """导航到nat列表页"""
        with allure.step(f"导航到:{region} NAT列表页"):
            super().navigate(region, self.nat_page.route)
            self.expect.to_have_title("NAT")


class DnsAliaseBusiness(BasePage):
    def __init__(self, page: Page):
        super().__init__(page)
        self.dns_aliase_page = DnsAliasePage(page)

    def navigate_to_dns_aliase_page(self, region=None):
        """导航到内网域名别名列表页"""
        with allure.step(f"导航到:{region} 内网域名别名列表页"):
            super().navigate(region, self.dns_aliase_page.route)
            self.expect.to_have_title("内网域名别名")
            self.expect.to_have_url(self.dns_aliase_page.route)


class IntranetRouterBusiness(BasePage):
    def __init__(self, page: Page):
        super().__init__(page)
        self.intranet_router_page = IntranetRouterPage(page)

    def navigate_to_intranet_router_page(self, region=None):
        """导航到边界路由器列表页"""
        with allure.step(f"导航到:{region} 边界路由器列表页"):
            super().navigate(region, self.intranet_router_page.route)
            self.expect.to_have_title("边界路由器")
            self.expect.to_have_url(self.intranet_router_page.route)


class SpanBusiness(BasePage):
    def __init__(self, page: Page):
        super().__init__(page)
        self.span_page = SpanPage(page)

    def navigate_to_span_page(self, region=None):
        with allure.step(f"导航到:{region} 网络流量镜像列表页"):
            super().navigate(region, self.span_page.route)
            self.expect.to_have_title("网络流量镜像")
            self.expect.to_have_url(self.span_page.route)


class SecurityGroupBusiness(BasePage):
    def __init__(self, page: Page, timeout=5000):
        super().__init__(page)
        self.security_group_page = SecurityGroupsPage(page)
        self.rule_subset_page = RuleSubsetPage(page)
        self.security_group_ipset_page = SecurityGroupIpsetsPage(page)

    def navigate_to_security_group_page(self, region=None) -> None:
        with allure.step(f"导航到:{region} 安全组列表页"):
            super().navigate(region, self.security_group_page.route)
            self.expect.to_have_title("安全组")
            self.expect.to_have_url(self.security_group_page.route)

    def navigate_to_security_group_rule_subset_page(self, region=None) -> None:
        with allure.step(f"导航到:{region} 安全组规则子集列表页"):
            route = (
                f"{self.security_group_page.route}/{self.rule_subset_page.route}"
            )
            super().navigate(region, route)
            self.expect.to_have_title("安全组")
            self.expect.to_have_url(route)

    def navigate_to_security_group_ipsets_page(self, region=None) -> None:
        with allure.step(f"导航到:{region} 安全组IP/端口集合列表页"):
            route = (
                f"{self.security_group_page.route}/{self.security_group_ipset_page.route}"
            )
            super().navigate(region, route)
            self.expect.to_have_title("安全组")
            self.expect.to_have_url(route)

    def delete_security_group_by_home(self, keyword: str) -> None:
        """在安全组主页删除安全组"""
        with allure.step(f"从安全组主页删除安全组:{keyword}"):
            self.table.click_checkbox_by_keyword(row_keyword=keyword)
            self.toolbar.more_operations_button()
            with self.page.expect_response(self.api_action("DeleteSecurityGroups"), timeout=self.api_timeout) as resp:
                self.toolbar.more_operations_button_to_delete("删除")
                alert_text_content = self.popout.get_alert_text_content()
                if alert_text_content:
                    self.popout.click_alert_confirm_button_if_element_visible()
                # self.page.wait_for_timeout(self.wait_response_timeout)
            response = resp.value
            res = response.json()
            log.debug(f"{res}")
            case_assert.assert_code(res)
            security_groups = res["security_groups"]
            log.info(f"删除的安全组ID为:{security_groups}")

    def delete_security_group_by_details_page(self) -> None:
        """在安全组主页详情页删除安全组"""
        with allure.step(f"从安全组详情页删除安全组"):
            self.security_group_page.details_page.click_detail_page_expand_button()
            with self.page.expect_response(self.api_action("DeleteSecurityGroups"), timeout=self.api_timeout) as resp:
                self.security_group_page.details_page.click_detail_page_expand_button_operation("删除")
                alert_text_content = self.security_group_page.details_page.get_alert_text_content()
                if alert_text_content:
                    self.popout.click_alert_confirm_button_by_role_link()
            response = resp.value
            res = response.json()
            log.debug(f"{res}")
            case_assert.assert_code(res)
            security_groups = res["security_groups"]
            log.info(f"删除的安全组ID为:{security_groups}")

    def modify_security_group_attribute(
            self,
            keyword: str = "",
            security_group_name: str = "",
            description: str = "",
            trust: bool = True,
    ) -> None:
        """
        修改安全组属性
        """
        with allure.step(f"修改安全组:{keyword}属性"):
            self.table.click_checkbox_by_keyword(row_keyword=keyword)
            self.toolbar.more_operations_button()
            self.toolbar.more_operations_button_to_delete("修改")
            self.security_group_page.input_security_group_name(security_group_name)
            self.security_group_page.click_enable_group_trust() if trust else \
                self.security_group_page.click_disable_group_trust()
            self.security_group_page.input_security_group_description(description)
            with self.page.expect_response(self.api_action("ModifySecurityGroupAttributes"),
                                           timeout=self.api_timeout) as resp:
                self.popout.click_submit_by_role_button()
                # self.page.wait_for_timeout(self.wait_response_timeout)
            response = resp.value
            res = response.json()
            log.debug(f"{res}")
            case_assert.assert_code(res)
            security_group_id = res["security_group_id"]
            log.info(f"修改的安全组ID为:{security_group_id}")
            return security_group_id

    def create_security_group(
            self, security_group_name="", trust=True, rules: List[Dict[str, str]] = None
    ) -> None:
        """
        :param security_group_name: 安全组的名称
        :param trust: 是否开启可信安全组
        :param rules: 安全组规则列表
        :return:
        """
        with allure.step(f"创建安全组,名称:{security_group_name},可信:{trust}"):
            self.security_group_page.click_create_security_groups_button()
            self.security_group_page.expect_create_security_group_title()
            self.security_group_page.input_security_group_name(security_group_name)
            self.security_group_page.click_enable_group_trust() if \
                trust else self.security_group_page.click_disable_group_trust()
            with self.page.expect_response(self.api_action("CreateSecurityGroup"), timeout=self.api_timeout) as resp:
                self.popout.click_submit_by_role_button()
                # self.page.wait_for_timeout(self.wait_response_timeout)
            response = resp.value
            res = response.json()
            log.debug(f"{res}")
            case_assert.assert_code(res)
            security_group_id = res["security_group_id"]
            log.info(f"创建的安全组ID为:{security_group_id}")
            self.security_group_page.wait_for_timeout(5000)
            if rules:
                self.add_sg_rule(rules)

    def add_sg_rule(self, rules: List[Dict[str, str]], apply: bool = True) -> None:
        """
        添加安全组规则
        :param rules: 安全组规则列表
        :param apply: 是否更新安全组
        :return:
        """
        with allure.step("添加安全组规则"):
            for rule in rules:
                security_group_rule_name = rule.get("security_group_rule_name", "")
                priority = rule.get("priority", 0)
                direction = rule.get("direction", 0)
                action = rule.get("action", "accept")
                protocol = rule.get("protocol", "tcp")
                start_port = rule.get("val1", "")
                end_port = rule.get("val2", "")
                source_ip = rule.get("val3", "")
                rule_action = rule.get("rule_action", "accept")
                self.security_group_page.details_page.click_add_security_group_rule_button()
                self.security_group_page.details_page.fill_sg_rule_name(
                    security_group_rule_name
                )
                self.security_group_page.details_page.fill_priority(priority)
                self.security_group_page.details_page.select_direction(direction)
                self.security_group_page.details_page.select_action(action)
                self.security_group_page.details_page.select_protocol(protocol)
                if protocol in ("icmp", "ipv6-icmp"):
                    self.security_group_page.details_page.select_icmp_type()
                    self.security_group_page.details_page.select_icmp_code()
                elif protocol in ("tcp", "udp"):
                    self.security_group_page.details_page.fill_start_port(start_port)
                    self.security_group_page.details_page.fill_end_port(end_port)
                self.security_group_page.details_page.fill_source_ip(source_ip)

                with self.page.expect_response(self.api_action("AddSecurityGroupRules"),
                                               timeout=self.api_timeout) as resp:
                    self.popout.click_submit_by_role_button()
                    # 获取警告名称
                    warning_text_content = self.popout.get_alert_warning_text_content()
                    if warning_text_content:
                        self.popout.click_alert_warning_button_if_element_visible()
                    # self.page.wait_for_timeout(self.wait_response_timeout)
                response = resp.value
                res = response.json()
                log.debug(f"{res}")
                case_assert.assert_code(res)
                security_group_rules = res["security_group_rules"]
                log.info(f"添加的安全组规则ID为:{security_group_rules}")
            if apply:
                self.apply_security_group()

    def apply_security_group(self) -> None:
        """
        应用更新安全组
        :return:
        """
        with allure.step("应用更新安全组"):
            with self.page.expect_response(self.api_action("ApplySecurityGroup"), timeout=self.api_timeout) as resp:
                self.security_group_page.details_page.click_apply_button()
                alert_text_content = self.security_group_page.details_page.get_alert_text_content()
                if alert_text_content:
                    self.popout.click_alert_confirm_button_by_role_link()
            response = resp.value
            res = response.json()
            log.debug(f"{res}")
            case_assert.assert_code(res)
            self.message.wait_message()
            self.wait_jobs(res, check_status=True)

    def import_security_group_rule(
            self, file_path: str, apply: bool = True
    ) -> List[str]:
        """
        导入安全组规则
        :param file_path: 导入文件路径
        :param apply: 是否更新安全组
        :return:
        """
        with allure.step("导入安全组规则"):
            self.security_group_page.details_page.click_more_operation_button()
            self.security_group_page.details_page.click_import_role_button()
            (
                security_group,
                security_group_rules,
            ) = self.security_group_page.details_page.click_import_file_button(file_path)
            if apply:
                self.apply_security_group()
            return security_group_rules

    def export_security_group(self) -> None:
        """
        导出安全组规则
        :return:
        """
        with allure.step("导出安全组规则"):
            self.security_group_page.details_page.click_more_operation_button()
            self.security_group_page.details_page.click_export_role_button()


class NetworkAclBusiness(BasePage):
    def __init__(self, page: Page):
        super().__init__(page)
        self.network_acl_page = NetworkAclPage(page)
        self.security_policie_page = SecurityPoliciePage(page)

    def navigate_to_network_access_control_page(self, region=None):
        with allure.step(f"导航到:{region} 网络访问控制列表页"):
            route = f"{self.network_acl_page.route}/{self.network_acl_page.sub_route}"
            super().navigate(region, route)
            self.expect.to_have_title("网络访问控制")
            self.expect.to_have_url(route)

    def navigate_to_network_access_control_security_policies_page(self, region=None):
        with allure.step(f"导航到:{region} 基础网络隔离策略列表页"):
            route = f"{self.network_acl_page.route}/{self.security_policie_page.route}"
            super().navigate(region, route)
            self.expect.to_have_title("网络访问控制")
            self.expect.to_have_url(route)


class VipBusiness(BasePage):
    def __init__(self, page: Page):
        super().__init__(page)
        self.vip_page = VipPage(page)

    def navigate_to_vip_page(self, region=None):
        with allure.step(f"导航到:{region} VIP列表页"):
            super().navigate(region, self.vip_page.route)
            self.expect.to_have_title("Console")
            self.expect.to_have_url(self.vip_page.route)
